
const DB = require('../config/Sequelize')
const BackCode = require("../utils/BackCode");
const { Op, QueryTypes } = require("sequelize");
const SecretTool = require('../utils/SecretTool')
const CodeEnum = require("../utils/CodeEnum");

const ProductService = {
    category: async () => {
        const data = await DB.Category.findAll({ 
            where: { pid: 0 },
            order: [['id']],
            include: [{ model: DB.Category, as: 'subCategoryList' }]
        })
        return BackCode.buildSuccessAndData({ data })
    },
    card: async () => {
        let cardList = await DB.ProductCard.findAll({ raw: true })
        let list = cardList.map(async (item) => {
            item.product_list = await DB.Product.findAll({ where: { id: item.product_list.split(',')}, raw: true  })
            return item
        })
        let lastList = await Promise.all(list)
        return BackCode.buildSuccessAndData({ data: lastList })
    },
    query_by_cid: async (cid, page, size, cpid) => {
        if (!(page && size)) return BackCode.buildError({ msg: '缺少必要的参数' })
        let sqlId = cid || cpid || null
        // 从第几条开始算起
        page = (page - 1) * size
        // 查询语句
        let productListSql = `SELECT p.* FROM product p LEFT JOIN category_product c ON c.product_id=p.id ${sqlId ? 'WHERE c.category_id=?' : ''}  ORDER BY p.gmt_create DESC LIMIT ?,?`
        let productQuery = sqlId ? [sqlId, page, size] : [page, size];
        const productList = await DB.sequelize.query(productListSql, {
            replacements: productQuery,
            type: QueryTypes.SELECT
        })
        // 查询课程总数
         // 通过子查询课程总数
        let totalSql = `select count(*) as total_record from (SELECT p.id FROM product p LEFT JOIN category_product c ON c.product_id=p.id ${sqlId ? 'WHERE c.category_id=?' : ''} group by p.id) temp_table`
        const totalRes = await DB.sequelize.query(totalSql, {
            replacements: [sqlId],
            type: QueryTypes.SELECT
        })
        // 总数
        let total_record = totalRes[0].total_record
        // 计算总页数
        let total_page = null
        total_record / size == 0 ? (total_page = total_record / size) : (total_page = Math.ceil(total_record / size))

        return BackCode.buildSuccessAndData({ data: { current_data: productList, total_page, total_record } })
    },
    detail: async (id) => {
        if(!id) return BackCode.buildError({ msg: '缺少必要的参数' })
        console.log('id: ', id);
        const detailRes = await DB.Product.findOne({
            where: { id },
            include: [{ model: DB.Teacher, as: 'teacherDetail' }]
        })
        return BackCode.buildSuccessAndData({ data: { ...detailRes.toJSON(), bd_zip_url: '', note_url: '' } })
    },
    chapter:async(id) =>{
        let chapterList = await DB.Chapter.findAll({where:{product_id:id},order:[['ordered']], raw:true})
        let episodeList = await DB.Episode.findAll({ where: { product_id: id }, order: [['ordered']], raw: true })
        // 将课程的集生成对象数组插入到章的每一项当中
        chapterList.map((item)=> {
            item['episodeList'] = []
            episodeList.map((subItem) => {
                if(item.id === subItem.chater_id) {
                    return item['episodeList'].push(subItem)
                }
            })
        })
        return BackCode.buildSuccessAndData({data:chapterList})
    },
    material_by_id: async (req) => {
        const {id} = req.query
        console.log('req.headers.authorization: ', req.headers);
        let token = req.headers.authorization.split(' ').pop()
        // 判断是否登录
        if (!token) {
          return BackCode.buildResult(CodeEnum.ACCOUNT_UNLOGIN)
        }
        let userInfo = SecretTool.jwtVerify(token)
        // 判断是否购买
        let orderList = await DB.ProductOrder.findAll({
          where: { product_id: id, account_id: userInfo.id, order_state: 'PAY' },
          raw: true
        })
        if (orderList.length > 0) {
          let productDetail = await DB.Product.findOne({
            attributes: ['bd_zip_url', 'note_url'],
            where: { id },
          })
          return BackCode.buildSuccessAndData({ data: productDetail })
        } else {
          return BackCode.buildError(CodeEnum.PRODUCT_NO_PAY)
        }
    },
    page: async (req) => {
        let { page, size, id } = req.body
        let { count, rows } = await DB.Comment.findAndCountAll({
          where: { product_id: id },
          order: [['gmt_create', 'DESC']],
          offset: Number((page - 1) * size),
          limit: Number(size)
        })
        let total_page = null
        count / size == 0 ? (total_page = count / size) : (total_page = Math.ceil(count / size))
        return BackCode.buildSuccessAndData({ current_data: rows, total_page: total_page, total_record: count })
    },
}
module.exports = ProductService